import hashlib

from license.models.device import Device
from project.settings import PRIMARY_DIR, COS_DIR
from license.utils.theseus_tool import TheseusTool
from license import constants as c
from asgiref.sync import sync_to_async, async_to_sync


# 异步任务
class AsyncTask:

    @staticmethod
    # 上传ts文件至cos
    async def upload_ts_file(machine_code: str, cert_data: str, reseller_id: int):
        args = [machine_code, cert_data, PRIMARY_DIR + "/" + "ts.plain.normal"]
        # TODO 日志处理
        # 云端文件的相对路径, ts加密数据
        file_path, ts_enc = TheseusTool.encode_ts(args)
        if not file_path:
            raise RuntimeError("TS encode fail")
        # 更新序列号数据
        # 设定ts文件url
        cos_key = file_path.replace(COS_DIR, "")
        # 对 ts_enc 进行MD5加密转换
        # 创建md5对象
        md5_hash = hashlib.md5(ts_enc)
        Device.objects.filter()
        # Device.objects.filter(reseller_id=reseller_id, machine_code=machine_code).update(
        #     ts_file_url=cos_key,
        #     ts_file_status=c.TS_STATUS_GENERATED,
        #     ts_file_hash_value=md5_hash.hexdigest()
        # )
        result = await sync_to_async(Device.objects.filter, thread_sensitive=True)(reseller_id=reseller_id,
                                                                                   machine_code=machine_code)
        await sync_to_async(result.update, thread_sensitive=True)(ts_file_url=cos_key,
                                                                  ts_file_status=c.TS_STATUS_GENERATED,
                                                                  ts_file_hash_value=md5_hash.hexdigest())
